package updown.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import updown.constant.GeneralConstant;
import updown.constant.LogConstant;
import updown.constant.MsgConstant;
import updown.controller.other.BaseController;
import updown.data.SseCacheData;
import updown.domain.*;
import updown.service.jar.LocalFileService;
import updown.service.jar.UploadJarService;
import updown.service.task.TaskInfoService;
import updown.util.RandomUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>Title: ww.kaixin.downupservice.controller </p>
 * <p>Description:updown: - 上传jar包到服务器 </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/3
 * @Version: 1.0
 */
@Controller
@RequestMapping("/uploadJar")
@Slf4j
public class UploadJarToServerController extends BaseController {

    @Autowired
    private SseCacheData sseCacheData;

    @Autowired
    private UploadJarService uploadJarService;

    @Autowired
    private LocalFileService localFileService;

    @Autowired
    private TaskInfoService taskInfoService;

    /**
     * 上传服务，同步到其他节点
     * @param file
     * @return
     */
    @PostMapping("/uploadJarAndSendToServer")
    @ResponseBody
    public String uploadJarAndSendToServer(MultipartFile file, HttpServletRequest request, ServiceMapVo vo) {
        log.info("uploadJarAndSendToServer(),file,request,vo:{}", file, request, vo);
//        // 1 创建任务
        SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
        String taskId = RandomUtil.getRandomStr();
        sseCacheData.put(taskId, sseEmitter);
        UploadJarService.sendToSeverIng.put(vo.getServiceName(),Boolean.TRUE);
        // 2 上传 jar包 到本地
        log.info("直接保存");
        String localPlace = localFileService.downToLocal(file, vo.getOriginalFileName(), vo.getServiceName(), vo.getJarVersionInfo(), taskId);
        log.info("直接保存,:{}", localPlace);
        // 3. 创建 serviceInfo 信息
        ServiceInfo serviceInfo = ServiceInfo.builder().serviceName(vo.getServiceName()).build();
        // 4 创建 task
        Jar jar = Jar.builder()
                .version(vo.getJarVersionInfo())
                .originalFileName(vo.getOriginalFileName())
                .localFileLocation(localPlace).build();

        TaskWrapper taskWrapper = TaskWrapper.builder().jar(jar)
                .taskId(taskId)
                .taskType(GeneralConstant.TASK_WRAPPER_TYPE)
                .serviceInfo(serviceInfo)
                .build();
        if (localPlace.startsWith(MsgConstant.fail)){
            log.info("uploadJarAndSendToServer() 文件在本地已存在");
            String msg = localPlace.substring(4,localPlace.length());
            sseCacheData.sendLastMsgAndCompleteInPool(msg,taskWrapper);
            UploadJarService.sendToSeverIng.remove(vo.getServiceName());
        }else {
            uploadJarService.sendJarInExecutor(taskWrapper);
        }
        log.info("提交任务，返回taskId成功:{}", taskId);
        addLog("上传Jar，同步到其他节点：" + vo.getServiceName(), LogConstant.MODULE_JAR_UPLOAD);
        return taskId;
    }

    /**
     * 上传服务jar 到本地
     * @param file
     * @return
     */
    @PostMapping("/uploadJarToLocal")
    @ResponseBody
    public String uploadJarToLocal(MultipartFile file, HttpServletRequest request, ServiceMapVo vo) {
        log.info("uploadJarToLocal(),file,request,vo:{}", file, request, vo);
        // 1 创建任务
        String taskId = RandomUtil.getRandomStr();
        // 2 上传 jar包 到本地
        TaskInfo saveToLocalTask = TaskInfo.builder().taskDes("上传jar到本地").build();
        String localPlace = localFileService.downToLocal(file, vo.getOriginalFileName(), vo.getServiceName(), vo.getJarVersionInfo(), taskId);
        log.info("直接保存:{}", localPlace);
        saveToLocalTask.finishedAddDes(localPlace);
        // 3. 创建 serviceInfo 信息
        ServiceInfo serviceInfo = ServiceInfo.builder().serviceName(vo.getServiceName()).build();
        // 4 创建 task
        Jar jar = Jar.builder()
                .version(vo.getJarVersionInfo())
                .originalFileName(vo.getOriginalFileName())
                .localFileLocation(localPlace).build();
        TaskWrapper taskWrapper = TaskWrapper.builder().jar(jar)
                .taskId(taskId)
                .taskType(GeneralConstant.TASK_WRAPPER_TYPE)
                .serviceInfo(serviceInfo)
                .build();
        taskWrapper.getTaskInfos().add(saveToLocalTask);

        if (localPlace.startsWith(MsgConstant.fail)){
            taskWrapper.endFail();
            taskInfoService.add(taskWrapper);
            return "本地文件已存在";
        }else {
            uploadJarService.sendJarInExecutor(taskWrapper);
            taskWrapper.endSuccess(Boolean.TRUE);
            taskInfoService.add(taskWrapper);
        }
        addLog("上传Jar，到本地：" + vo.getServiceName(), LogConstant.MODULE_JAR_UPLOAD);
        return "上传到本地成功";
    }
}
